package com.cw.demo.netty.server;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * RPC服务端
 *
 * @author chenw
 * @date 2021/1/7
 */
@Slf4j
public class RpcServer {
    private String ip;
    private int port;
    /** 用于处理网络流的读写线程 */
    private int ioThreads;
    /** 用户业务处理的操作线程 */
    private int workThreads;

    public RpcServer(String ip, int port, int ioThreads, int workThreads) {
        this.ip = ip;
        this.port = port;
        this.ioThreads = ioThreads;
        this.workThreads = workThreads;
    }

    public void start() {
        //bossgroup,用于处理客户端的连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup(ioThreads);
        //workergroup，用来处理与各个客户端连接的io操作
        EventLoopGroup workerGroup = new NioEventLoopGroup(workThreads);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {

            serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                            .addLast(new StringDecoder());
                        socketChannel.pipeline()
                            .addLast(new StringEncoder());
                        socketChannel.pipeline()
                            .addLast(new RpcServerHandler());
                    }
                });
            //客户端套接字接受队列大小
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 100)
                //避免端口冲突
                .option(ChannelOption.SO_REUSEADDR, true)
                //关闭小流合并，保证消息的及时性
                .option(ChannelOption.TCP_NODELAY, true)
                //长时间没动静的连接自动关闭
                .option(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture channelFuture = serverBootstrap.bind(port)
                .sync();
            log.info("server start listen at {}", port);
            channelFuture.channel()
                .closeFuture()
                .sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
        serverBootstrap.bind(this.ip, this.port)
            .addListener(future -> {
                if (future.isSuccess()) {
                    log.info("Rpc Server Startup success");
                } else {
                    log.info("RpcServer Startup failed", future.cause());
                }
            });
    }

    public static void main(String[] args) {
        RpcServer rpcServer = new RpcServer("127.0.0.1", 8090, 1, 1);
        rpcServer.start();
    }
}
